package wind.autotest.database.suport;

import java.util.Hashtable;

import com.sun.jna.Library;
import com.sun.jna.Memory;
import com.sun.jna.Native;

/**
 * 密码服务
 */
public class DBPasswordCenterAgency {
    
    private static Hashtable<String, String> hashTalbe = new Hashtable<String, String>();
    
    public static abstract interface IGetDBPasswordCenter extends Library {
        
        public static final IGetDBPasswordCenter INSTANCE = (IGetDBPasswordCenter) Native.loadLibrary("CryptoCPP", IGetDBPasswordCenter.class);
        
        public abstract int GetCredential(String paramString1, String paramString2, Memory paramMemory, int paramInt);
    }
    
    public static String GetPassword(String dbSource, String userID) {
    
        StringBuilder sb = new StringBuilder();
        sb.append(dbSource).append('\\').append(userID);
        String key = sb.toString();
        if (hashTalbe.containsKey(key)) {
            return ((String) hashTalbe.get(key)).toString();
        }
        try {
			return GetLastedPassword(dbSource, userID);
		} catch (InterruptedException e) {
			return "";
		}
    }
    
    public static String GetLastedPassword(String dbSource, String userID) throws InterruptedException {
    
        Memory memory = new Memory(50L);
        int length = 50;
        int result = IGetDBPasswordCenter.INSTANCE.GetCredential(dbSource, userID, memory, length);
        int i = 0;
        while (i < 3) {
            if (result <= 0) {
                result = IGetDBPasswordCenter.INSTANCE.GetCredential(dbSource, userID, memory, length);
            }
            if (result > memory.getSize()) {
                memory.clear();
                memory = new Memory(result + 5);
                length = result + 5;
                result = IGetDBPasswordCenter.INSTANCE.GetCredential(dbSource, userID, memory, length);
            }
            if (result > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append(dbSource).append('\\').append(userID);
                String key = sb.toString();
                String password = memory.getString(0L);
                hashTalbe.put(key, password);
                return password;
            }
            i++;
            
            Thread.sleep(5000L);
        }
        return "";
    }
    
    public static void main(String[] args) throws Exception {
    
        String ip = args[0];
        String userName = args[1];
        String passwd = GetLastedPassword(ip, userName);
        if ((passwd != null) && (passwd.length() != 0)) {
            System.out.println("����������������");
        }
        else {
            System.out.println("����������������");
        }
    }
}
